import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['X-Token'] = getToken()
      config.params = {
        token: getToken(),
        ...config.params
      }
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  res => {
    switch (res.status) {
      case 200:
        break
      case 201:
        // Message.success('保存成功')
        break
      case 202:
        // Message.success('保存成功')
        break
      case 204:
        Message.success('删除成功')
        break
      case 400:
        Message.warning('请求错误')
        break
      case 401:
        Message.info('用户名或密码错误')
        break
      case 403:
        Message.info('禁止访问')
        break
      case 404:
        Message.info('请求不存在')
        break
      case 422:
        console.log('code:422', res)
        break
      default:
    }
    return res.data
  },
  error => {

    if (error.response) {
      console.log(error.response.status, error.response.data.message) // for debug
    }

    if (error && error.response) {
      switch (error.response.status) {
        case 401:
          removeToken()
          callback.reLogin('您的登录已过期，请重新登录')
          break
        case 500:
          Message.error('内部服务器错误:'+error.response.data.message)
          break
        case 404:
          Message.error('请求路径不存在')
          break
        default:
          Message.error('未知错误')
          console.log('未知错误', error.response)
      }
    } else {
      console.log(error)
      Message.error('连接超时!')
    }

    return Promise.reject(error.response ? error.response.data.message : error)
  }
)
const callback = {
  reLogin(tip) {
    MessageBox.confirm(tip, '提示', {
      confirmButtonText: '去登录',
      cancelButtonText: '继续停留',
      type: 'warning'
    }).then(() => {
      store.dispatch('user/frontLogOut').then(() => {
        location.reload()
      })
    })
  }

}

export default service
